'''
                           _ooOoo_
                         o8888888o
                           88" . "88
                            (| ^_^ |)
                           O\  =  /O
                      ____/`---'\____
                          .'  \\|     |//  `.
                         /  \\|||  :  |||//  \
                       /  _||||| -:- |||||-  \
                        |   | \\\  -  /// |   |
                       | \_|  ''\---/''  |   |
                     \  .-\__  `-`  ___/-. /
                  ___`. .'  /--.--\  `. . ___
           ."" '<  `.___\_<|>_/___.'  >'"".
                | | :  `- \`.;`\ _ /`;.`/ - ` : | |
              \  \ `-.   \_ __\ /__ _/   .-` /  /
         佛祖保佑       永无BUG     永不修改
 '''

 #库导入
import sensor, image, time
from pyb import UART, LED

#补光程序
LED(1).on()
LED(2).on()
LED(3).on()

#阈值
THRESHOLD = (59, 100, -31, 8, -40, 38)

#识别区域 宽度28 长度40
roil = [(0, 45, 28, 40),#左1
           (32, 0, 28, 40),#左2
           (65, 0, 28, 40),#中
           (98, 0, 28, 40),#右1
           (132, 45, 28, 40),#右2
          ]

#摄像头初始化
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QQVGA)
sensor.skip_frames(time = 2000)

#时钟初始化
clock = time.clock()

#uart初始化
uart = UART(3,115200)
uart.init(115200, bits=8, parity=None, stop=1)

#数据打包函数
def outuart(a, b, c, d, e):
    global uart
    #发送数据
    uart.write("@")
    uart.write(str(a))
    uart.write(",")
    uart.write(str(b))
    uart.write(",")
    uart.write(str(c))
    uart.write(",")
    uart.write(str(d))
    uart.write(",")
    uart.write(str(e))
    uart.write(",")
    uart.write('\r')
    uart.write('\n')

#主函数
while(True):
    clock.tick()
    img = sensor.snapshot()

    #阈值自适应
    histogram = img.get_histogram()
    Thresholds = histogram.get_threshold()
    l = Thresholds.l_value()
    img.binary([(0, l)])

    for rec in roil:
        img.draw_rectangle(rec, color=(200,57,100))

    flag = [0,0,0,0,0]

    blob1=None
    blob2=None
    blob3=None
    blob4=None
    blob5=None

    blob1 = img.find_blobs([THRESHOLD], roi=roil[0])
    blob2 = img.find_blobs([THRESHOLD], roi=roil[1])
    blob3 = img.find_blobs([THRESHOLD], roi=roil[2])
    blob4 = img.find_blobs([THRESHOLD], roi=roil[3])
    blob5 = img.find_blobs([THRESHOLD], roi=roil[4])

    if blob1:
        flag[0] = 1
    if blob2:
        flag[1] = 1
    if blob3:
        flag[2] = 1
    if blob4:
        flag[3] = 1
    if blob5:
        flag[4] = 1

    print(flag[0],flag[1],flag[2],flag[3],flag[4])
    outuart(flag[0], flag[1], flag[2], flag[3], flag[4])
